package com.jk.utils;
 
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * 类: HttpClient <br>
 * 描述: httpclient工具类 <br>
 * 作者: song<br>
 * 时间: 2017年7月21日 下午3:15:27
 */
public class HttpClientUtil02 {
	
	static CloseableHttpClient client = null;
	static {
		//1、创建httpClient实例
		client = HttpClients.createDefault();
	}
	
	/**
	 * 
	 * 方法: get <br>
	 * 描述: get请求 <br>
	 * 作者: Teacher song<br>
	 * 时间: 2017年7月21日 下午3:15:25
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String get(String url,HashMap<String, Object> params){
/*		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("name", "张三");
		params.put("age", 18);*/
		try {
			//2、创建get对象
			HttpGet httpGet = new HttpGet();
			
			//3、拼接完成的get请求路径
			//a、hashmap的遍历：获取里面的key和value
			//b、拼接StringBuffer
			Set<String> keySet = params.keySet();
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append(url).append("?t=").append(System.currentTimeMillis());
			for (String key : keySet) {
				stringBuffer.append("&").append(key).append("=").append(params.get(key));
			}
			
			httpGet.setURI(new URI(stringBuffer.toString()));
			//4、执行execute方法，发送请求
			CloseableHttpResponse execute = client.execute(httpGet);
			//5、获取请求的状态码
			int statusCode = execute.getStatusLine().getStatusCode();
			//判断请求是否成功
			if (200 != statusCode) {
				return "";
			}
			return EntityUtils.toString(execute.getEntity(), "utf-8");
		}catch (Exception e) {
			//6、关闭连接
			try {
				client.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * 方法: post <br>
	 * 描述: post请求 <br>
	 * 作者: Teacher song<br>
	 * 时间: 2017年7月21日 下午3:20:31
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String post(String url,HashMap<String, Object> params) {
		try {
			//创建post请求对象
			HttpPost httpPost = new HttpPost();
			//设置路径
			httpPost.setURI(new URI(url));
			
			//设置post请求参数
			//a、hashmap的遍历：获取里面的key和value
			//b、拼接list
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				NameValuePair e = new BasicNameValuePair(key, params.get(key).toString());
				parameters.add(e);
			}
			
			HttpEntity entity = new UrlEncodedFormEntity(parameters , "utf-8");
			httpPost.setEntity(entity);
			
			//执行：发送请求
			CloseableHttpResponse execute = client.execute(httpPost);
			//获取请求的状态码
			int statusCode = execute.getStatusLine().getStatusCode();
			if (200 != statusCode) {
				return "";
			}
			return EntityUtils.toString(execute.getEntity(), "utf-8");
		}catch (Exception e) {
			//6、关闭连接
			try {
				client.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 发送短信验证码：给header传参
	 */
	public static String post2(String url,HashMap<String, Object> params,HashMap<String, Object> HeaderParams) {
		try {
			//创建post请求对象
			HttpPost httpPost = new HttpPost();
			//设置路径
			httpPost.setURI(new URI(url));
			
			//设置请求的header
			Set<String> headerKey = HeaderParams.keySet();
			for (String key : headerKey) {
				httpPost.addHeader(key, HeaderParams.get(key).toString());
			}
			
			//设置post请求参数
			//a、hashmap的遍历：获取里面的key和value
			//b、拼接list
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				NameValuePair e = new BasicNameValuePair(key, params.get(key).toString());
				parameters.add(e);
			}
			
			HttpEntity entity = new UrlEncodedFormEntity(parameters , "utf-8");
			httpPost.setEntity(entity);
			
			//执行：发送请求
			CloseableHttpResponse execute = client.execute(httpPost);
			//获取请求的状态码
			int statusCode = execute.getStatusLine().getStatusCode();
			if (200 != statusCode) {
				return "";
			}
			return EntityUtils.toString(execute.getEntity(), "utf-8");
		}catch (Exception e) {
			//6、关闭连接
			try {
				client.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
			e.printStackTrace();
			return null;
		}
	}
	//使用post3将对象转为字符串  然后后台接口使用@requestBody注解
	public static String post3(String url,String jsonStr) {
		try {
			//创建post请求对象
			HttpPost httpPost = new HttpPost();
			//设置路径
			httpPost.setURI(new URI(url));
			
			//设置post请求参数
			//设置content-type属性：application/json： JSON数据格式
			httpPost.addHeader("Content-Type", "application/json");
			
			StringEntity stringEntity = new StringEntity(jsonStr,  "utf-8");
			httpPost.setEntity(stringEntity);			
			
			//执行：发送请求
			CloseableHttpResponse execute = client.execute(httpPost);
			//获取请求的状态码
			int statusCode = execute.getStatusLine().getStatusCode();
			if (200 != statusCode) {
				return "";
			}
			return EntityUtils.toString(execute.getEntity(), "utf-8");
		}catch (Exception e) {
			//6、关闭连接
			try {
				client.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 发送短信
	 */
		public static String sendCode(String phoneNumber) {
			String url = "https://api.netease.im/sms/sendcode.action";
			HashMap<String, Object> headerParams = new HashMap<String, Object>();
			//开发者平台分配的appkey
			String appKey = "91e595010a4b97bcb7c6ebffa43c573d";
			//随机数6位  100000 999999
			long nonce = Math.round(((Math.random()*899999+100000)));
			//当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
			long curTime = System.currentTimeMillis()/1000;
			//SHA1(AppSecret + Nonce + CurTime)，三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)
			String appSecret = "0340e96ce258";
			String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce+"", curTime+"");
			headerParams.put("AppKey", appKey);
			headerParams.put("Nonce", nonce);
			headerParams.put("CurTime", curTime);
			headerParams.put("CheckSum", checkSum);
			headerParams.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

			
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("mobile",phoneNumber);
			params.put("templateid","19471247");
			params.put("authCode",nonce);
			String str = HttpClientUtil02.post2(url, params, headerParams);
			JSONObject parseObject = JSONObject.parseObject(str);
			int code = parseObject.getIntValue("code");
			return str;
		}

}
